import React, { useCallback, useEffect, useMemo, useRef } from "react";
import { Box, SxProps } from "@mui/system";
import CircleWrapper from "../../../../../Common/CircleWrapper";
import { CaretRightOutlined } from "@ant-design/icons";
export interface VideoPreviewProps extends Omit<React.VideoHTMLAttributes<any>, "style"> {
  sx?: SxProps;
  posterTime?: number; //指定预览图的时间，默认0秒处
}
const VideoPreview = ({ sx, src, posterTime = 10, onClick, ...otr }: VideoPreviewProps) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {}, [src]);
  const getPoster = useCallback(() => {
    if (canvasRef.current && videoRef.current) {
      const ctx = canvasRef.current.getContext("2d");
      canvasRef.current.width = videoRef.current.videoWidth;
      videoRef.current.currentTime = posterTime;
      canvasRef.current.height = videoRef.current.videoHeight;
      ctx!.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height);
      const posterDataUrl = canvasRef.current.toDataURL("image/jpeg");
      // 将生成的预览图像数据用作封面
      videoRef.current.setAttribute("poster", posterDataUrl);
    }
  }, []);
  return (
    <Box sx={{ height: 80, position: "relative", width: 80, ...sx }}>
      <CircleWrapper sx={{ height: 36, width: 36 }}>
        <CaretRightOutlined height={24} width={24} style={{ color: "white" }} />
      </CircleWrapper>
      <video style={{ height: "inherit", width: "inherit", objectFit: "cover" }} onLoadedData={getPoster} ref={videoRef} src={src} {...otr}></video>
      <canvas ref={canvasRef} id='canvas' style={{ display: "none" }}></canvas>
    </Box>
  );
};
export default VideoPreview;
